import { URL_PREFIX } from '@/constants';
import { catchError, map, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';


function requestFlow(type: string, url: string, data?: any) {
	const config: any = {
		url: URL_PREFIX + url,
		method: type,
		withCredentials: true,
		headers: {
			'Content-Type': 'application/json;charset=utf-8'
		}
	};
	if (type === 'post') {
		config['body'] = data
	} else if (type === 'get' && data) {
		let ret = '?';
		for (let it in data) {
			ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
		}
		ret = ret.substring(0, ret.length - 1);
		config.url += ret;
	}
	return ajax(config).pipe(
		// retry(1),	// 重试
		map(data => data.response),
		catchError(err => {
			console.log(err)
			return of(err)
		})
	);
}

export {
	requestFlow
}
